package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.MediaFeign;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-28
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private IApUserService apUserService;
    @Autowired
    private MediaFeign mediaFeign;
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult queryByPage(AuthDto authDto) {
//        1.构建分页查询对象
        IPage<ApUserRealname> page = new Page<>(authDto.getPage(),authDto.getSize());
//        2.构建查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(authDto.getStatus())) {
            wrapper.eq(ApUserRealname::getStatus,authDto.getStatus());
        }
//        3.执行查询方法
        this.page(page,wrapper);
//        4.封装响应数据
        return new PageResponseResult(authDto.getPage(),authDto.getSize(),page.getTotal(),page.getRecords());
    }

    /**
     * 管理员人工审核实名认证信息
     * @param authDto
     * @param type    操作类型 1：通过  2：驳回
     * @return
     */
    @Override
    @GlobalTransactional  //事务处理
    public ResponseResult auth(AuthDto authDto, int type) {
//        1.修改本服务对应账户信息
//        1.1根据实名认证记录id查询
        ApUserRealname apUserRealname = this.getById(authDto.getId());
//        1.2修改实名认证表状态(未通过)
        if (type==2){
            apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_FAIL.getVal());
            apUserRealname.setReason(authDto.getReason());
            this.updateById(apUserRealname);
            return ResponseResult.errorResult(200,"审核已驳回");
        }
//        1.3修改app用户表状态
//        1.3.1根据社交用户id查询用户
        ApUser apUser = apUserService.getById(apUserRealname.getUserId());
//        1.3.2更新状态
        apUser.setIsIdentityAuthentication(true);
        apUser.setFlag(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
        apUserService.updateById(apUser);
//        1.4修改实名认证状态（通过）
        apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        this.updateById(apUserRealname);
//        2.远程调用自媒体微服务新增自媒体用户
        WmUser wmUser = createWmuser(apUser);
//        3.远程调用作者微服务新增作者用户
        if (wmUser!=null) {
            ApAuthor apAuthor = createAuthor(apUser, wmUser);
            if (apAuthor!=null){
//              3.1远程调用自媒体微服务更新自媒体用户逻辑外键author_id
                wmUser.setApAuthorId(apAuthor.getId());
                mediaFeign.updateWmUser(wmUser);
                return ResponseResult.okResult();
            }
        }
        return ResponseResult.errorResult(500,"审核失败，请联系管理员");
    }



    /**
     * 构建自媒体用户对象；远程保存自媒体用户
     * @param apUser
     * @return
     */
    private WmUser createWmuser(ApUser apUser) {
//        1.创建自媒体对象
        WmUser wmUser = new WmUser();
//        1.1复制社交用户的基本属性
        BeanUtils.copyProperties(apUser,wmUser);
//        1.2手动赋值属性
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        wmUser.setType(0);
        wmUser.setScore(0);
//        2.远程调用自媒体对象完成新增
        ResponseResult<WmUser> responseResult = mediaFeign.saveWmUser(wmUser);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
        WmUser data = responseResult.getData();
        return data;
        }
        return null;
    }

    /**
     * 构建作者用户对象；远程保存作者用户
     * @param apUser
     * @param wmUser
     * @return
     */
    private ApAuthor createAuthor(ApUser apUser, WmUser wmUser) {
//        1.创建作者对象
        ApAuthor apAuthor = new ApAuthor();
//        1.1手动赋值属性
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());
        apAuthor.setType(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
        apAuthor.setName(apUser.getName());
//        2.远程调用作者对象完成新增
        ResponseResult<ApAuthor> responseResult = articleFeign.saveApAuthor(apAuthor);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApAuthor data = responseResult.getData();
            return data;
        }
        return null;
    }
}
